package com.chinaums.study.fileupload.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @RequestMapping(value = "/{type}", method = RequestMethod.POST)
    public Map<String, String> uploadCert(@PathVariable final String type, final String desc,
                                          @RequestPart("file") Part file, final HttpServletRequest request) throws Exception {
        if (file == null) {
            throw new ServletException("文件上传失败，缺少请求参数：file");
        }
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (final InputStream in = file.getInputStream()) {
            IOUtils.copy(in, out);
        }
        final Map<String, String> response = new HashMap<>();
        response.put("文件类型", type);
        response.put("摘要", desc);
        response.put("文件大小", String.format("%dK", out.toByteArray().length >> 10));
        response.put("应答消息", "文件上传成功");
        return response;
    }
}
